﻿using System;
using System.Collections.Generic;
using Gumini.JulaDB.DataTypes;

namespace Gumini.JulaDB.Expressions
{
    /// <summary>
    /// Checking if the value is [not] null.
    /// </summary>
    internal class IsNullCondition : Expression
    {
        private readonly bool _negate;

        /// <param name="negate">If true, this corresponds to IS NOT NULL.</param>
        public IsNullCondition(bool negate, Expression child)
            : base(child)
        {
            _negate = negate;
        }

        public Expression Child
        {
            get { return base._children[0]; }
        }
        
        public override TypedValue Evaluate(List<Context<TypedValue>> contexts)
        {
            var childIsNull = Child.Evaluate(contexts).IsNull;
            if (_negate)
                childIsNull = !childIsNull;
            return new TypedValue(DataType.Bool, childIsNull);
        }

        public override DataType InferType(Context<DataType> context)
        {
            return DataType.Bool;
        }

        public override bool Equals(Expression other)
        {
            var b = other as IsNullCondition;
            if (b == null)
                return false;
            return
                this._negate == b._negate &&
                this.Child.Equals(b.Child);
        }

        public override string ToString()
        {
            return String.Format("({0} IS{1} NULL)", this.Child, _negate ? " NOT" : String.Empty);
        }
    }
}
